import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'dart:convert';
import '../models/server_config.dart';
import '../l10n/app_localizations.dart';
import '../utils/theme.dart';

class ShareConfigDialog extends StatelessWidget {
  final ServerConfig server;

  const ShareConfigDialog({
    super.key,
    required this.server,
  });

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);

    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      child: Container(
        constraints: const BoxConstraints(maxWidth: 400),
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        AppTheme.primaryColor,
                        AppTheme.primaryColor.withOpacity(0.7),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Icon(
                    Icons.share,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        l10n.translate('quick_share_config'),
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        server.name,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            const SizedBox(height: 24),

            // 分享选项
            _buildShareOption(
              context,
              icon: Icons.link,
              title: l10n.translate('quick_copy_link'),
              subtitle: 'Copy configuration link',
              color: Colors.blue,
              onTap: () {
                _copyLink(context, l10n);
              },
            ),
            const SizedBox(height: 12),
            _buildShareOption(
              context,
              icon: Icons.qr_code,
              title: 'Show QR Code',
              subtitle: 'Display QR code for scanning',
              color: Colors.green,
              onTap: () {
                _showQRCode(context, l10n);
              },
            ),
            const SizedBox(height: 12),
            _buildShareOption(
              context,
              icon: Icons.content_copy,
              title: 'Copy JSON',
              subtitle: 'Copy full configuration as JSON',
              color: Colors.orange,
              onTap: () {
                _copyJSON(context, l10n);
              },
            ),
            const SizedBox(height: 12),
            _buildShareOption(
              context,
              icon: Icons.send,
              title: 'Share to App',
              subtitle: 'Share via other apps',
              color: Colors.purple,
              onTap: () {
                _shareToApp(context, l10n);
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildShareOption(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required Color color,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade200),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(icon, color: color, size: 24),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
            Icon(Icons.chevron_right, color: Colors.grey.shade400),
          ],
        ),
      ),
    );
  }

  void _copyLink(BuildContext context, AppLocalizations l10n) {
    // 生成配置链接 (vmess://...)
    final configLink = _generateConfigLink();
    Clipboard.setData(ClipboardData(text: configLink));
    
    Navigator.pop(context);
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Row(
          children: [
            Icon(Icons.check_circle, color: Colors.white),
            SizedBox(width: 12),
            Text('Configuration link copied to clipboard'),
          ],
        ),
        backgroundColor: AppTheme.secondaryColor,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
  }

  void _showQRCode(BuildContext context, AppLocalizations l10n) {
    final configLink = _generateConfigLink();
    
    // 调试输出
    print('QR Code Data: $configLink');
    print('QR Code Length: ${configLink.length}');
    
    Navigator.pop(context);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        title: Row(
          children: [
            Icon(Icons.qr_code_2, color: AppTheme.primaryColor),
            const SizedBox(width: 8),
            const Text('QR Code'),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 真实的二维码
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Colors.grey.shade300, width: 2),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: configLink.isNotEmpty
                    ? ClipRect(
                        child: QrImageView(
                          data: configLink,
                          size: 250.0,
                          backgroundColor: Colors.white,
                          foregroundColor: Colors.black,
                          errorCorrectionLevel: QrErrorCorrectLevel.M,
                          padding: EdgeInsets.all(8),
                        ),
                      )
                    : SizedBox(
                        width: 250,
                        height: 250,
                        child: Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.error_outline,
                                size: 64,
                                color: Colors.red.shade300,
                              ),
                              const SizedBox(height: 16),
                              Text(
                                'Unable to generate QR code',
                                style: TextStyle(color: Colors.red.shade700),
                              ),
                            ],
                          ),
                        ),
                      ),
              ),
              const SizedBox(height: 16),
              Text(
                server.name,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Text(
                  '${server.address}:${server.port}',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey.shade700,
                    fontFamily: 'monospace',
                  ),
                ),
              ),
              const SizedBox(height: 12),
              Text(
                'Scan to import configuration',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey.shade600,
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton.icon(
            onPressed: () {
              Clipboard.setData(ClipboardData(text: configLink));
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: const Row(
                    children: [
                      Icon(Icons.check_circle, color: Colors.white, size: 20),
                      SizedBox(width: 12),
                      Text('Link copied to clipboard'),
                    ],
                  ),
                  backgroundColor: AppTheme.primaryColor,
                  behavior: SnackBarBehavior.floating,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              );
            },
            icon: const Icon(Icons.copy),
            label: Text(l10n.translate('quick_copy_link')),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(l10n.translate('action_cancel')),
          ),
        ],
      ),
    );
  }

  void _copyJSON(BuildContext context, AppLocalizations l10n) {
    final configJson = _generateConfigJSON();
    Clipboard.setData(ClipboardData(text: configJson));
    
    Navigator.pop(context);
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Row(
          children: [
            Icon(Icons.check_circle, color: Colors.white),
            SizedBox(width: 12),
            Text('JSON configuration copied to clipboard'),
          ],
        ),
        backgroundColor: Colors.orange,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
  }

  void _shareToApp(BuildContext context, AppLocalizations l10n) {
    final configLink = _generateConfigLink();
    
    // 这里应该使用 share_plus 包来实现真实的分享功能
    // 目前先复制到剪贴板
    Clipboard.setData(ClipboardData(text: configLink));
    
    Navigator.pop(context);
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Share feature coming soon!'),
            SizedBox(height: 4),
            Text(
              'Configuration link has been copied to clipboard',
              style: TextStyle(fontSize: 12),
            ),
          ],
        ),
        backgroundColor: Colors.purple,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        duration: const Duration(seconds: 3),
      ),
    );
  }

  String _generateConfigLink() {
    try {
      // 生成 vmess:// 或其他协议链接
      final config = {
        'v': '2',
        'ps': server.name,
        'add': server.address,
        'port': server.port.toString(),
        'id': server.userId,
        'aid': server.alterId,
        'net': server.network,
        'type': 'none',
        'host': server.host ?? '',
        'path': server.path ?? '',
        'tls': server.security == 'tls' ? 'tls' : '',
      };

      final jsonStr = json.encode(config);
      final base64Str = base64.encode(utf8.encode(jsonStr));
      final result = '${server.protocol}://$base64Str';
      
      print('=== QR Code Generation ===');
      print('Config JSON: $jsonStr');
      print('Base64: $base64Str');
      print('Final Link: $result');
      print('Link Length: ${result.length}');
      
      return result;
    } catch (e) {
      print('Error generating config link: $e');
      return '';
    }
  }

  String _generateConfigJSON() {
    final config = {
      'name': server.name,
      'protocol': server.protocol,
      'address': server.address,
      'port': server.port,
      'userId': server.userId,
      'alterId': server.alterId,
      'security': server.security,
      'network': server.network,
      'path': server.path,
      'host': server.host,
    };

    const encoder = JsonEncoder.withIndent('  ');
    return encoder.convert(config);
  }
}
